﻿using System;
using System.Net;
using FluentValidation;
using Grundy.Common;
using Grundy.Message;
using Grundy.Message.Licensing;

namespace Grundy.Licensing.Server.Command
{
    public class CheckinCommand : ICommand
    {
        private readonly LicenseSessionStore _licenseSessionStore;
        private static CheckinRequestValidator _validator = new CheckinRequestValidator();

        public CheckinCommand(LicenseSessionStore licenseSessionStore)
        {
            _licenseSessionStore = licenseSessionStore;
        }

        public bool CanProcess(Request request)
        {
            return request is CheckinRequest;
        }

        public Response Process(Request request, EndPoint requestingEndPoint, Guid customerId, string customerName)
        {
            return Process((CheckinRequest)request, requestingEndPoint);
        }
        
        private Response Process(CheckinRequest request, EndPoint requestingEndPoint)
        {
            _validator.ValidateAndThrow(request);

            var lri = new LicenseRequestInformation { ClientSessionId = request.SessionId, EndPoint = requestingEndPoint};
            var successful = _licenseSessionStore.Checkin(lri);

            string message = successful ? null : "Could not find session with id {0}.".FormatWith(request.SessionId);
         

            return new CheckinSucceededResponse { CheckinSuccessful = successful, Message = message};
        }
    }
}